import { Button, Form, Input, message, Popover, Table, Tag } from "antd";
import type { ColumnsType } from "antd/es/table";
import { ListIcon, PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiUserAuthorList } from "~/api/author";
import { apiRolesList } from "~/api/role";
import Filter from "~/components/ui/filter";
import Title from "~/components/ui/title";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IPageData } from "~/types/common";
import type { IFilter, IUserAuthor } from "~/types/manage/content/author";
import UserAuthorModal from "./manage/content/author/user-author-modal";

export default function Page() {
  const [filterForm] = Form.useForm<IFilter>();
  const [userList, setUserList] = useState<IPageData<IUserAuthor> | null>(null);

  const tableHeight = useTableHeight(351);
  const [loading, setLoading] = useState(false);

  const [modalVisible, setModalVisible] = useState(false);
  const [editUserAuthor, setEditUserAuthor] = useState<IUserAuthor | null>(
    null,
  );

  const [roleMap, setRoleMap] = useState<Map<number, string>>();

  const _handler = {
    addAuthor: () => {
      setModalVisible(true);
      setEditUserAuthor(null);
    },
    editAuthor: (user: IUserAuthor) => {
      setModalVisible(true);
      setEditUserAuthor(user);
    },
  };

  const _fetch = {
    init: async () => {
      const roleList = await apiRolesList();
      setRoleMap(new Map(roleList.map((item) => [item.id, item.name])));
      _fetch.users(filterForm.getFieldsValue(true));
    },
    users: async (params: IFilter) => {
      setLoading(true);
      try {
        const resp = await apiUserAuthorList(params);
        setUserList(resp);
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      } finally {
        setLoading(false);
      }
    },
  };

  const _ui: {
    tableColumns: ColumnsType<IUserAuthor>;
  } = {
    tableColumns: [
      {
        title: "序号",
        dataIndex: "index",
        fixed: "left",
        width: 40,
        render: (_, __, index) => {
          return index + 1;
        },
      },
      {
        title: "姓名",
        dataIndex: ["real", "realName"],
        fixed: "left",
        width: 100,
      },
      {
        title: "笔名",
        dataIndex: ["authors"],
        width: 120,
        render: (_, record) => {
          const defaultPenName =
            record.authors.find((item) => item.isDefault)?.penName ||
            record.authors[0].penName;
          if (record.authors.length > 1) {
            return (
              <Popover
                title={"笔名列表"}
                content={
                  <div className="flex flex-col gap-2">
                    {record.authors.map((item) => {
                      return (
                        <div className="flex items-center gap-2 rounded bg-gray-100 p-2 text-sm">
                          {item.penName}
                          {item.isDefault && <Tag color="green">默认</Tag>}
                        </div>
                      );
                    })}
                  </div>
                }
              >
                <div className="flex w-full cursor-pointer items-center gap-2">
                  <ListIcon size={18} className="text-gray-400" />
                  {defaultPenName}
                </div>
              </Popover>
            );
          }
          return defaultPenName;
        },
      },
      {
        title: "邮箱",
        dataIndex: "email",
        width: 120,
      },
      {
        title: "手机号",
        dataIndex: "mobile",
        width: 120,
      },
      {
        title: "角色",
        dataIndex: ["roleIds"],
        width: 100,
        render: (value: number[]) => {
          return (value || [])
            .map((item) => roleMap?.get(item) || "")
            .join(",");
        },
      },
      {
        title: "操作",
        key: "action",
        fixed: "right",
        width: 100,
        render: (_, record) => {
          return (
            <div className="flex items-center justify-end gap-2">
              <Button
                type="link"
                onClick={() => {
                  _handler.editAuthor(record);
                }}
              >
                编辑
              </Button>
            </div>
          );
        },
      },
    ],
  };

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <>
      <div className="flex h-full w-full">
        <div className="flex flex-1 flex-col gap-4 overflow-hidden">
          <Title
            title="作者"
            buttonGroups={[
              <Button
                type="primary"
                onClick={() => {
                  _handler.addAuthor();
                }}
              >
                <PlusIcon size={18} />
                添加作者
              </Button>,
            ]}
          />
          <Filter
            form={filterForm}
            initialValues={{
              pageNum: 1,
              pageSize: 100,
            }}
            onSearch={() => {
              _fetch.users(filterForm.getFieldsValue(true));
            }}
            onReset={() => {
              _fetch.users(filterForm.getFieldsValue(true));
            }}
          >
            {/* <Form.Item label={"姓名"} name={"realName"}>
              <Input />
            </Form.Item> */}
            <Form.Item label={"笔名"} name={"penName"}>
              <Input />
            </Form.Item>
          </Filter>
          <div className="h-full w-full">
            <Table
              loading={loading}
              scroll={{
                y: tableHeight,
                x: "max-content",
              }}
              rowKey={(record) => record.id}
              columns={_ui.tableColumns}
              dataSource={userList?.list || []}
              locale={{
                emptyText: "暂无数据",
              }}
              pagination={{
                showTotal: (total, range) => {
                  return `共 ${total} 条`;
                },
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 100,
                showSizeChanger: true,
                onChange(page, pageSize) {
                  filterForm.setFieldsValue({
                    pageNum: page,
                    pageSize: pageSize,
                  });
                  _fetch.users(filterForm.getFieldsValue(true));
                },
                pageSize: userList?.pageSize,
                current: userList?.pageNum,
                total: userList?.total,
              }}
            />
          </div>
        </div>
      </div>
      <UserAuthorModal
        visible={modalVisible}
        userAuthor={editUserAuthor}
        onCancel={() => {
          setModalVisible(false);
          setEditUserAuthor(null);
        }}
        onOk={() => {
          setModalVisible(false);
          _fetch.users(filterForm.getFieldsValue(true));
        }}
      />
    </>
  );
}
